﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ComponentModel.DataAnnotations;

using Whoever.Framework.Attributes;

namespace Whoever.Framework.Utils
{
    public static class ReflectionHelper
    {
        public static Dictionary<PropertyInfo, object> GetAttributes(object obj, Type attributeType)
        {
            var attributes = new Dictionary<PropertyInfo, object>();

            foreach (PropertyInfo property in obj.GetType().GetProperties())
            {
                var attribute = property.GetCustomAttributes(attributeType, true).ToList();
                foreach (object o in attribute)
                    attributes.Add(property, o);
            }

            return attributes;
        }

        public static bool ContainAttribute(PropertyInfo property, Type attributeType)
        {
            foreach (var attribute in property.GetCustomAttributes(true))
                if (attributeType.ToString() == attribute.GetType().ToString())
                    return true;

            return false;
        }

        public static string GetKeyName(Type entityType)
        {
            foreach (PropertyInfo property in entityType.GetProperties())
                if (ContainAttribute(property, typeof(IdentityField)) || ContainAttribute(property, typeof(KeyAttribute)))
                    return property.Name;

            return string.Empty;
        }
    }
}
